from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.animation import FFMpegWriter

# 准备数据
date = [20200317, 20200318, 20200319,  # 日期
        20200320, 20200321, 20200322, 20200323,
        20200324, 20200325, 20200326, 20200327,
        20200328, 20200329, 20200330, 20200331,
        20200401, 20200402, 20200403, 20200404,
        20200405]

values = [926.0, 822.0, 737.0, 592.0, 506.0,  # 中国新增确诊人数
          459.0, 458.0, 492.0, 405.0, 541.0, 385.0, 478.0,
          337.0, 288.0, 190.0, 195.0, 175.0, 199.0, 226.0,
          138.0]

# 准备横轴数据
x = list(range(len(date)))

# 创建画布
fig = plt.figure(figsize=(18, 10))

# 初始化折线图和坐标轴
line, = plt.plot([], [], color='r', marker='o')

# 设置y轴范围
plt.ylim(0, max(values))
# 设置x轴范围
x_range = 10
plt.xlim(0, x_range)
plt.xticks(x[0:x_range], date[0:x_range], fontsize=7)

# 定义变量，用于记录每一帧显示不能超过几条数据
line_range = 6


# 动画更新函数
def update(i):
    # 更新折线图
    # 起始位置
    start = 0 if i - line_range < 0 else i - line_range
    # 结束位置
    end = i + 1
    line.set_data(x[start:end], values[start:end])

    if i > line_range:
        # 计算横轴的结束索引
        x_end = start + x_range if start + x_range < len(x) else len(x)
        plt.xlim(start, x_end)
        plt.xticks(x[start:x_end], date[start:x_end], fontsize=7)
    return line


# 创建动画
animation = FuncAnimation(fig, update, frames=x, repeat=False)

# 保存动画
FFwriter = FFMpegWriter(fps=5, extra_args=['-vcodec', 'libx264'])
animation.save('折线图动画.mp4', writer=FFwriter)
# animation.save('折线图动画.gif', fps=5, writer='ablat')

# plt.show()
